package com.the_ring.chapter06.util;

import android.content.Context;

import androidx.datastore.core.DataStore;
import androidx.datastore.preferences.core.MutablePreferences;
import androidx.datastore.preferences.core.Preferences;
import androidx.datastore.preferences.core.PreferencesKeys;
import androidx.datastore.preferences.rxjava2.RxPreferenceDataStoreBuilder;
import androidx.datastore.rxjava2.RxDataStore;

import io.reactivex.Flowable;
import io.reactivex.Single;

public class DataStoreUtil {

    private RxDataStore<Preferences> mDataStore;

    public static DataStoreUtil instance;

    private DataStoreUtil(Context context) {
        mDataStore = new RxPreferenceDataStoreBuilder(context.getApplicationContext(), "datastore").build();
    }

    // 创建数据仓库工具的实例
    public static DataStoreUtil getInstance(Context context) {
        if (instance == null) {
            instance = new DataStoreUtil(context);
        }
        return instance;
    }

    // 获取指定名称的字符串
    public String getStringValue(String key) {
        Preferences.Key<String> keyId = PreferencesKeys.stringKey(key);
        Flowable<String> flow = mDataStore.data().map(prefs -> prefs.get(keyId));
        try {
            return flow.blockingFirst();
        } catch (Exception e) {
            return "";
        }
    }

    // 设置指定名称的字符串值
    public void setStringValue(String key, String value) {
        Preferences.Key<String> keyId = PreferencesKeys.stringKey(key);
        Single<Preferences> result = mDataStore.updateDataAsync(prefs -> {
            MutablePreferences mutablePrefs = prefs.toMutablePreferences();
            mutablePrefs.set(keyId, value);
            return Single.just(mutablePrefs);
        });
    }
}
